/**
create: James
time: 2022.8.21
to:商品
 */

// 导入数据库操作模块
const db = require('../db/index')

// 获取类别列表
exports.getCategoryList = (req,res) =>{
	const params = parseInt(req.query.id)
	const sql = 'select * from category'
	db.query(sql,[params],(err,results)=>{
		if(err) return res.lose(err)
		res.send({
			message:'获取商品类别数据成功',
			success:true,
			status:0,
			result:results
		})
	})
}

// 设置类别相关信息
exports.updateCategory = (req, res) => {
	const type = req.method
	const { id, pid, name, order = 0, status = 1, create_time = new Date() } = req.body
	const pId = req.params.id
	let sql = ''
	let sqlValue = []
	let val = '新增'
	if (type === 'POST') {
		val = '新增'
		sql = 'INSERT INTO category (pid, name, `order`, status, create_time) VALUES (?, ?, ?, ?, ?)'
		sqlValue = [pid, name, order, status, create_time]
	} else if (type === 'PUT') {
		val = '修改'
		sql = 'UPDATE category SET pid = ?, name = ?, `order` = ?, status = ?, create_time = ?, update_time = ? WHERE id = ?'
		sqlValue = [pid, name, order, status, create_time, new Date(), id]
		if (pId) {
			sql = 'UPDATE category SET status = ?, update_time = ? WHERE id = ?'
			sqlValue = [status, new Date(), pId]
		}
	} else if (type === 'DELETE') {
		val = '删除'
		sql = 'DELETE FROM category WHERE id = ?'
		sqlValue = [pId]
	}
	if(req.headers.token === '11111111') {
		console.log(sql, sqlValue)
		db.query(sql, sqlValue, (err, results) => {
			console.log(results)
			if (err) return res.status(500).lose(err)
			if (results && results.affectedRows) {
				req.body.id = results.insertId
				res.send({
					message: pId ? '类别状态修改成功' : `${val}类别成功`,
					status: 200
				})
			} else {
				res.status(500).send({
					message: `${val}类别失败`,
					result: 'error'
				})
			}
		})
	} else {
		res.status(500).send({
			message: '无权限',
			status: 505
		})
	}
}

// 获取商品规格列表
exports.getSpecsList = (req,res) =>{
	const {
		page=1,
		limit=10
	} = req.query
	
	const sql = 'select * from specs ORDER BY CAST(SUBSTRING_INDEX(id, "A", -1) AS UNSIGNED) ASC LIMIT ? OFFSET ?'
	const offset = (page - 1) * limit;
	console.log(limit, offset, sql)
	db.query(sql, [limit*1, offset], (err, results) => {
		if (err) return res.lose(err)
		db.query(`SELECT COUNT(*) AS total FROM user_level`, (err, totalResults) => {
			const totalCount = totalResults[0].total;
			if (results && results.length) {
				if(req.headers.token === '11111111') {
					res.send({
						message: '获取商品规格成功',
						status: 200,
						result: {
							list: results.sort((a,b) => a.id - b.id),
							totalCount,
						}
					})
				} else {
					res.status(500).send({
						message: '无权限',
						status: 505
					})
				}
			} else {
				res.status(500).send({
					message: '获取商品规格失败',
					result: 'error'
				})
			}
		})
	})
}

// 设置商品规格相关
exports.setSpecs = async (req, res) => {
	const type = req.method
	const { id, name, defaultValue, order = 0, status = 1, create_time = new Date() } = req.body
	const pId = req.params.id
	let sql = ''
	let sqlValue = []
	let val = '新增'
	if (type === 'POST') {
		val = '新增'
		sql = 'INSERT INTO specs (name, `default`, status, `order`) VALUES (?, ?, ?, ?)'
		sqlValue = [name, defaultValue, status, order]
	} else if (type === 'PUT') {
		console.log(req.params)
		val = '修改'
		sql = 'UPDATE specs SET name = ?, `default` = ?, status = ?, `order`= ? WHERE id = ?'
		sqlValue = [name, defaultValue, status, order, id]
		// 如果只修改状态
		if (pId) {
			sql = 'UPDATE specs SET status = ? WHERE id = ?'
			sqlValue = [status, pId]
		}
	} else if (type === 'DELETE') {
		val = '删除'
		console.log(req.query)
		// 构建批量删除的SQL语句
		const ids = req.query.ids || [];
		console.log('ids',ids)
		// 构建IN子句
		const placeholders = ids.map(() => '?').join(', ');
		sql = `DELETE FROM specs WHERE id IN (${placeholders})`;
		sqlValue= ids
	}
	if(req.headers.token === '11111111') {
		db.query(sql, sqlValue, (err, results) => {
			console.log(sql, sqlValue, results)
			if (err) return res.status(500).lose(err)
			if (results && results.affectedRows) {
				req.body.id = results.insertId
				res.send({
					message: pId ? '商品规格状态修改成功' : `${val}商品规格成功`,
					status: 200
				})
			} else {
				res.status(500).send({
					message: `${val}商品规格失败`,
					result: 'error'
				})
			}
		})
	} else {
		res.status(500).send({
			message: '无权限',
			status: 505
		})
	}
}


// 获取根据商品id轮播图
exports.getShopCarousel = (req,res) =>{
	const params = parseInt(req.query.id)
	const sql = 'select * from shopdetailimg where shop_id = ?'
	db.query(sql,[params],(err,results)=>{
		if(err) return res.lose(err)
		res.send({
			message:'获取商品详情轮播图数据成功',
			success:true,
			status:0,
			result:results
		})
	})
}

// 获取根据商品id商品信息
exports.getShopInfo = (req,res) =>{
	const params = parseInt(req.query.id)
	const sql = 'select * from hotshop where id = ?'
	db.query(sql,[params],(err,results)=>{
		if(err) return res.lose(err)
		res.send({
			message:'获取商品信息数据成功',
			success:true,
			status:0,
			result:results
		})
	})
}